<template>
  <div class="email-config-container">
    <div class="page-header">
      <h1 class="page-title">📧 邮箱配置</h1>
      <p class="page-subtitle">配置您的邮箱以接收巡检报告</p>
    </div>

    <!-- 配置表单 -->
    <div class="config-form">
      <div class="form-group">
        <label class="form-label">
          <span class="label-text">邮件服务商</span>
          <span class="required">*</span>
        </label>
        <select v-model="formData.email_provider" @change="onProviderChange" class="form-input">
          <option value="163">163邮箱</option>
          <option value="qq">QQ邮箱</option>
          <option value="gmail">Gmail</option>
          <option value="outlook">Outlook</option>
          <option value="custom">自定义</option>
        </select>
        <p class="form-hint">选择您使用的邮箱服务商</p>
      </div>

      <div class="form-group">
        <label class="form-label">
          <span class="label-text">发件邮箱地址</span>
          <span class="required">*</span>
        </label>
        <input 
          v-model="formData.email_address" 
          type="email" 
          class="form-input" 
          placeholder="example@163.com"
          required>
        <p class="form-hint">用于发送巡检报告的邮箱地址</p>
      </div>

      <div class="form-group">
        <label class="form-label">
          <span class="label-text">SMTP服务器</span>
          <span class="required">*</span>
        </label>
        <input 
          v-model="formData.smtp_server" 
          type="text" 
          class="form-input" 
          placeholder="smtp.163.com"
          :disabled="formData.email_provider !== 'custom'"
          required>
        <p class="form-hint">邮件服务器地址</p>
      </div>

      <div class="form-row">
        <div class="form-group" style="flex: 1;">
          <label class="form-label">
            <span class="label-text">SMTP端口</span>
            <span class="required">*</span>
          </label>
          <input 
            v-model.number="formData.smtp_port" 
            type="number" 
            class="form-input" 
            placeholder="465"
            :disabled="formData.email_provider !== 'custom'"
            required>
          <p class="form-hint">通常为465或587</p>
        </div>

        <div class="form-group" style="flex: 1;">
          <label class="form-label checkbox-label">
            <input 
              v-model="formData.use_ssl" 
              type="checkbox" 
              class="form-checkbox">
            <span class="label-text">使用SSL加密</span>
          </label>
          <p class="form-hint">推荐开启以提高安全性</p>
        </div>
      </div>

      <div class="form-group">
        <label class="form-label">
          <span class="label-text">授权码</span>
          <span class="required">*</span>
        </label>
        <div class="password-input-wrapper">
          <input 
            v-model="formData.authorization_code" 
            :type="showPassword ? 'text' : 'password'"
            class="form-input" 
            placeholder="请输入邮箱授权码"
            required>
          <button 
            type="button" 
            @click="showPassword = !showPassword" 
            class="toggle-password">
            {{ showPassword ? '🙈' : '👁️' }}
          </button>
        </div>
        <p class="form-hint warning">
          ⚠️ 注意：这里需要填写邮箱的<strong>授权码</strong>，不是邮箱登录密码！
        </p>
      </div>

      <div class="form-group">
        <label class="form-label checkbox-label">
          <input 
            v-model="formData.is_active" 
            type="checkbox" 
            class="form-checkbox">
          <span class="label-text">启用此邮箱配置</span>
        </label>
      </div>

      <!-- 按钮组 -->
      <div class="button-group">
        <button 
          @click="testConnection" 
          class="btn btn-secondary"
          :disabled="isTesting || !isFormValid">
          <span v-if="isTesting">⏳ 测试中...</span>
          <span v-else>🔍 测试连接</span>
        </button>

        <button 
          @click="saveConfig" 
          class="btn btn-primary"
          :disabled="isSaving || !isFormValid">
          <span v-if="isSaving">💾 保存中...</span>
          <span v-else>💾 保存配置</span>
        </button>
      </div>

      <!-- 发送巡检报告按钮（仅在已保存配置后显示） -->
      <div v-if="configId" class="send-report-section">
        <div class="section-divider"></div>
        <p class="section-hint">✅ 邮箱已配置，现在可以发送巡检报告了</p>
        <button 
          @click="goToDashboard" 
          class="btn btn-send-report">
          📊 返回仪表盘发送报告
        </button>
      </div>

      <!-- 测试结果 -->
      <div v-if="testResult" :class="['test-result', testResult.type]">
        <span class="result-icon">{{ testResult.type === 'success' ? '✅' : '❌' }}</span>
        <span>{{ testResult.message }}</span>
      </div>
    </div>

    <!-- 163邮箱授权码获取指南 -->
    <div class="help-section">
      <h2 class="help-title">📖 163邮箱授权码获取指南</h2>
      <div class="help-content">
        <div class="help-step">
          <div class="step-number">1</div>
          <div class="step-content">
            <h3>登录163邮箱</h3>
            <p>访问 <a href="https://mail.163.com" target="_blank">mail.163.com</a> 并登录您的账号</p>
          </div>
        </div>

        <div class="help-step">
          <div class="step-number">2</div>
          <div class="step-content">
            <h3>进入设置</h3>
            <p>点击页面右上角的"设置" → "POP3/SMTP/IMAP"</p>
          </div>
        </div>

        <div class="help-step">
          <div class="step-number">3</div>
          <div class="step-content">
            <h3>开启SMTP服务</h3>
            <p>找到"POP3/SMTP服务"并勾选开启</p>
          </div>
        </div>

        <div class="help-step">
          <div class="step-number">4</div>
          <div class="step-content">
            <h3>获取授权码</h3>
            <p>点击"新增授权密码"，按照提示发送短信验证，即可获得授权码</p>
          </div>
        </div>

        <div class="help-step">
          <div class="step-number">5</div>
          <div class="step-content">
            <h3>复制授权码</h3>
            <p>将获得的授权码复制并填入上方的"授权码"输入框中</p>
          </div>
        </div>
      </div>

      <div class="help-note">
        <strong>💡 提示：</strong>
        <ul>
          <li>授权码不同于邮箱登录密码，请妥善保管</li>
          <li>如果忘记授权码，可以重新生成</li>
          <li>163邮箱SMTP服务器：smtp.163.com，端口：465（SSL）或25</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import api from '../services/api'

const router = useRouter()

// 表单数据
const formData = ref({
  email_provider: '163',
  email_address: '',
  smtp_server: 'smtp.163.com',
  smtp_port: 465,
  use_ssl: true,
  authorization_code: '',
  is_active: true
})

// 状态
const isSaving = ref(false)
const isTesting = ref(false)
const showPassword = ref(false)
const testResult = ref(null)
const configId = ref(null)

// 邮箱服务商配置
const providerConfig = {
  '163': { smtp_server: 'smtp.163.com', smtp_port: 465, use_ssl: true },
  'qq': { smtp_server: 'smtp.qq.com', smtp_port: 465, use_ssl: true },
  'gmail': { smtp_server: 'smtp.gmail.com', smtp_port: 587, use_ssl: false },
  'outlook': { smtp_server: 'smtp.office365.com', smtp_port: 587, use_ssl: false },
  'custom': { smtp_server: '', smtp_port: 465, use_ssl: true }
}

// 表单验证
const isFormValid = computed(() => {
  return formData.value.email_address &&
         formData.value.smtp_server &&
         formData.value.smtp_port &&
         formData.value.authorization_code &&
         formData.value.authorization_code.length >= 6
})

// 服务商变化
const onProviderChange = () => {
  const config = providerConfig[formData.value.email_provider]
  if (config && formData.value.email_provider !== 'custom') {
    formData.value.smtp_server = config.smtp_server
    formData.value.smtp_port = config.smtp_port
    formData.value.use_ssl = config.use_ssl
  }
}

// 加载配置
const loadConfig = async () => {
  try {
    const response = await api.get('/email-configs/my_config/')
    if (response) {
      configId.value = response.id
      formData.value = {
        email_provider: response.email_provider || '163',
        email_address: response.email_address || '',
        smtp_server: response.smtp_server || 'smtp.163.com',
        smtp_port: response.smtp_port || 465,
        use_ssl: response.use_ssl !== undefined ? response.use_ssl : true,
        authorization_code: response.authorization_code || '',
        is_active: response.is_active !== undefined ? response.is_active : true
      }
    }
  } catch (error) {
    // 如果返回404，说明还没有配置，这是正常情况
    if (error.response?.status !== 404) {
      console.error('加载邮箱配置失败:', error)
    }
  }
}

// 测试连接
const testConnection = async () => {
  if (!isFormValid.value) {
    alert('请填写完整的邮箱配置信息')
    return
  }

  isTesting.value = true
  testResult.value = null

  try {
    const response = await api.post('/email-configs/test_connection/', formData.value)
    testResult.value = {
      type: 'success',
      message: response.message
    }
  } catch (error) {
    testResult.value = {
      type: 'error',
      message: error.response?.data?.error || '测试失败: ' + error.message
    }
  } finally {
    isTesting.value = false
  }
}

// 保存配置
const saveConfig = async () => {
  if (!isFormValid.value) {
    alert('请填写完整的邮箱配置信息')
    return
  }

  isSaving.value = true
  testResult.value = null

  try {
    if (configId.value) {
      // 更新已有配置
      await api.put(`/email-configs/${configId.value}/`, formData.value)
      alert('✅ 邮箱配置更新成功！')
    } else {
      // 创建新配置
      const response = await api.post('/email-configs/', formData.value)
      configId.value = response.id
      alert('✅ 邮箱配置保存成功！')
    }
  } catch (error) {
    console.error('保存邮箱配置失败:', error)
    alert('保存失败: ' + (error.response?.data?.error || error.message))
  } finally {
    isSaving.value = false
  }
}

// 跳转到仪表盘
const goToDashboard = () => {
  router.push('/dashboard')
}

onMounted(() => {
  loadConfig()
})
</script>

<style scoped>
.email-config-container {
  padding: 20px;
  max-width: 900px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-title {
  font-size: 36px;
  color: var(--color-accent-pink);
  margin-bottom: 10px;
  font-weight: 700;
}

.page-subtitle {
  font-size: 16px;
  color: var(--color-text-secondary);
}

/* 配置表单 */
.config-form {
  background: var(--color-bg-secondary);
  padding: 30px;
  border-radius: 20px;
  box-shadow: var(--shadow-card);
  margin-bottom: 30px;
}

.form-group {
  margin-bottom: 24px;
}

.form-row {
  display: flex;
  gap: 20px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  color: var(--color-text-primary);
  font-weight: 600;
  font-size: 14px;
}

.label-text {
  margin-right: 4px;
}

.required {
  color: #ff6b6b;
}

.form-input {
  width: 100%;
  padding: 12px 16px;
  background: var(--color-bg-primary);
  border: 2px solid var(--color-border);
  border-radius: 12px;
  color: var(--color-text-primary);
  font-size: 14px;
  transition: all 0.3s;
}

.form-input:focus {
  outline: none;
  border-color: var(--color-accent-pink);
  box-shadow: 0 0 0 3px rgba(255, 107, 157, 0.1);
}

.form-input:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.password-input-wrapper {
  position: relative;
}

.toggle-password {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  cursor: pointer;
  font-size: 18px;
  padding: 4px 8px;
  transition: transform 0.2s;
}

.toggle-password:hover {
  transform: translateY(-50%) scale(1.1);
}

.form-hint {
  margin-top: 6px;
  font-size: 12px;
  color: var(--color-text-secondary);
}

.form-hint.warning {
  color: #ffa94d;
  display: flex;
  align-items: center;
  gap: 6px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  user-select: none;
}

.form-checkbox {
  width: 20px;
  height: 20px;
  cursor: pointer;
  accent-color: var(--color-accent-pink);
}

/* 按钮组 */
.button-group {
  display: flex;
  gap: 15px;
  margin-top: 30px;
}

.btn {
  flex: 1;
  padding: 14px 24px;
  border: none;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: var(--shadow-soft);
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-primary {
  background: linear-gradient(135deg, var(--color-accent-pink), var(--color-accent-purple));
  color: white;
}

.btn-primary:hover:not(:disabled) {
  transform: translateY(-3px) scale(1.02);
  box-shadow: var(--shadow-hover);
}

.btn-secondary {
  background: var(--color-bg-primary);
  color: var(--color-text-primary);
  border: 2px solid var(--color-accent-cyan);
}

.btn-secondary:hover:not(:disabled) {
  background: var(--color-accent-cyan);
  color: white;
  transform: translateY(-3px);
}

/* 测试结果 */
.test-result {
  margin-top: 20px;
  padding: 16px 20px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 14px;
  animation: slideIn 0.3s ease-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.test-result.success {
  background: #d3f9d8;
  color: #2b8a3e;
  border: 2px solid #51cf66;
}

.test-result.error {
  background: #ffe0e0;
  color: #c92a2a;
  border: 2px solid #ff6b6b;
}

.result-icon {
  font-size: 20px;
}

/* 帮助指南 */
.help-section {
  background: var(--color-bg-secondary);
  padding: 30px;
  border-radius: 20px;
  box-shadow: var(--shadow-card);
}

.help-title {
  font-size: 24px;
  color: var(--color-accent-purple);
  margin-bottom: 24px;
  font-weight: 700;
}

.help-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.help-step {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.step-number {
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, var(--color-accent-pink), var(--color-accent-purple));
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  font-weight: 700;
  flex-shrink: 0;
}

.step-content h3 {
  font-size: 16px;
  color: var(--color-text-primary);
  margin-bottom: 8px;
  font-weight: 600;
}

.step-content p {
  font-size: 14px;
  color: var(--color-text-secondary);
  line-height: 1.6;
}

.step-content a {
  color: var(--color-accent-cyan);
  text-decoration: none;
  font-weight: 600;
}

.step-content a:hover {
  text-decoration: underline;
}

.help-note {
  margin-top: 24px;
  padding: 20px;
  background: var(--color-bg-primary);
  border-left: 4px solid var(--color-accent-cyan);
  border-radius: 8px;
}

.help-note strong {
  color: var(--color-accent-cyan);
  font-size: 16px;
  display: block;
  margin-bottom: 12px;
}

.help-note ul {
  margin: 0;
  padding-left: 24px;
}

.help-note li {
  color: var(--color-text-secondary);
  font-size: 14px;
  line-height: 1.8;
}

/* 发送报告区域 */
.send-report-section {
  margin-top: 30px;
  padding-top: 30px;
  text-align: center;
}

.section-divider {
  height: 2px;
  background: linear-gradient(90deg, transparent, var(--color-border), transparent);
  margin-bottom: 20px;
}

.section-hint {
  color: var(--color-accent-success);
  font-size: 16px;
  margin-bottom: 20px;
  font-weight: 600;
}

.btn-send-report {
  background: linear-gradient(135deg, var(--color-accent-cyan), #4dabf7);
  color: white;
  padding: 14px 32px;
  font-size: 16px;
}

.btn-send-report:hover:not(:disabled) {
  background: linear-gradient(135deg, #4dabf7, var(--color-accent-cyan));
  transform: translateY(-3px) scale(1.05);
}
</style>
